// logs.js
import {
  ble_send_date
} from "../../utils/util.js";
const app = getApp()
Page({
  data: {
    bluetoothName: 'Louvide',
    deviceId: '',
    serviceId: '',
    characteristicId: '',
    isConnecting: false,
    isConnected: false,
    foundDevices: [],
    connectedDevice: null
  },

  // 搜索附近蓝牙设备
  async onSearchConnect() {
    const that = this;
    this.setData({
      isConnecting: true,
      foundDevices: []
    });
    wx.showLoading({
      title: '正在搜索...'
    });
    ///蓝牙初始化
    wx.openBluetoothAdapter({
      success() {
        wx.hideLoading();
        wx.showLoading({
          title: '正在搜索...'
        });
        console.log("openBluetoothAdapter");
        wx.startBluetoothDevicesDiscovery({
          allowDuplicatesKey: false,
          success() {
            console.log("startBluetoothDevicesDiscovery");
            setTimeout(() => {
              wx.getBluetoothDevices({
                success(res) {
                  console.log("getBluetoothDevices");
                  wx.hideLoading();
                  const name = that.data.bluetoothName.trim();
                  const found = res.devices.filter(d => d.name && d.name.indexOf(name) !== -1);
                  console.log(found);
                  that.setData({
                    foundDevices: found
                  });
                  // if (found.length != 0) {
                  //   that.setData({
                  //     foundDevices: [found[found.length - 1]]
                  //   });
                  // }

                  if (found.length === 0) {
                    wx.showModal({
                      title: '提示',
                      content: '没有搜索到设备，请重试',
                    })
                  }
                },
                complete() {
                  wx.stopBluetoothDevicesDiscovery(); // 停止搜索
                  that.setData({
                    isConnecting: false
                  });
                }
              });
            }, 2000);
          }
        });
      },
      fail() {
        wx.showModal({
          title: '提示',
          content: '请检查手机蓝牙是否打开',
          success(res) {
            if (res.confirm) {
              wx.reLaunch({
                url: '../logs/logs',
              })
            }
          }
        })
        wx.hideLoading();
        that.setData({
          isConnecting: false
        });
      }
    });
  },


  //用户点击 连接指定蓝牙设备
  onConnectDevice(e) {
    console.log(e);
    const deviceId = e.currentTarget.dataset.deviceid;
    const that = this;
    wx.showLoading({
      title: '连接中...'
    });
    wx.createBLEConnection({
      deviceId,
      success() {
        wx.hideLoading();
        that.setData({
          deviceId,
          isConnected: true,
          foundDevices: [], // 连接后清空设备列表
        });

        console.log('[蓝牙连接] 连接成功，设备ID:', deviceId);

        wx.stopBluetoothDevicesDiscovery(); // 停止搜索

        // 监听特征值变化 接收数据包
        that.listenForBLEValueChange();
        // 获取服务和特征值
        that.discoverServicesAndCharacteristics(deviceId);

        wx.showToast({
          title: '连接成功',
          icon: 'success',
          duration: 1000,
          complete(res) {
            //连接成功跳转到主页
            wx.switchTab({
              url: '../index/index',
            })
          }
        });

        that.isConnection();




      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: '连接失败',
          icon: 'none'
        });
        console.error('[蓝牙连接] 连接失败:', err);
      }
    });
  },

  isConnection() {
    //监听设备连接状态
    wx.onBLEConnectionStateChange(function (res) {
      console.log(res)
      if (res.connected == false) {

        

        wx.showToast({
          title: '设备连接已断开',
          icon: 'none'
        });
        // wx.showModal({
        //   title: '提示',
        //   content: '设备连接已断开',
        //   success(res) {
        //     wx.reLaunch({
        //       url: '../logs/logs',
        //     })
        //   }
        // })
        //清空设备ID 特征ID vuex
        let {
          bleUser
        } = app.store.getState();

        let deviceId = bleUser.deviceId;
        if (deviceId) {
          wx.closeBLEConnection({
            deviceId,
            success (res) {
              console.log(res)
            }
          })
        }

        bleUser = {},
          app.store.setState({
            bleUser
          });
        /**********************************/

      }
    })
  },

  onSendData() {
    wx.switchTab({
      url: '../index/index',
    })
    return

    let buffer = new ArrayBuffer(5); //申请数组长度
    let dataView = new DataView(buffer);
    dataView.setInt8(0, 2025);
    dataView.setInt8(1, 6);
    dataView.setInt8(2, 7);
    dataView.setInt8(3, 8);
    dataView.setInt8(4, 9);
    //上述相当于小程序发送了 list = [100,101] ,  蓝牙设备这边也正常收到了buffer = [100,101]  ，其他数据也是这样发。
    //按正常10进制的方式发即可、  
    let {
      bleUser
    } = this.data.$state;
    let deviceId = bleUser.deviceId;
    let serviceId = bleUser.serviceId;
    let characteristicId = bleUser.characteristicId;
    console.log(deviceId, serviceId, characteristicId);
    wx.writeBLECharacteristicValue({
      deviceId,
      serviceId,
      characteristicId,
      value: buffer,
      success: () => {
        console.log('[蓝牙发送] 发送成功');
        wx.showToast({
          title: '发送成功',
          icon: 'success'
        });
      },
      fail: () => {
        console.log('[蓝牙发送] 发送失败');
        wx.showToast({
          title: '发送失败',
          icon: 'none'
        });
      }
    });
  },

  ab2hex(buffer) {
    let hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },

  // 监听蓝牙数据
  listenForBLEValueChange() {
    const that = this;
    let listBuffer; //接收到的数据
    let list = [];
    let decimal;
    wx.onBLECharacteristicValueChange(function (res) {
      //console.log('[蓝牙接收] 收到数据:', res);
      listBuffer = that.ab2hex(res.value).match(/.{1,2}/g);
      for (let i = 0; i < listBuffer.length; i++) {
        decimal = parseInt(listBuffer[i], 16)
        list.push(decimal);
      }
      console.log(list);
      //把接收到的数据存进wxministore
      let {
        bleStore
      } = app.store.getState();
      if (list[0] != 170) { //包头判断 如果不是这个包头0xAA return
        list = [];
        return;
      }
      if (list[1] == 1 || list[1] == 2 || list[1] == 3) {
        that.update_alarm_list(list) //接收到数据 处理一下给闹钟页面展示
      } else if (list[1] == 4) {//全部数据接收
        bleStore[0] = list[2];
        bleStore[1] = list[3];
        bleStore[2] = list[4];
        bleStore[3] = list[5];
        bleStore[4] = list[6];
        bleStore[5] = list[7];
        bleStore[6] = list[8];
        bleStore[7] = list[9];
        bleStore[8] = list[10];
        bleStore[9] = list[11];
        bleStore[10] = list[12];
        bleStore[11] = list[13];
        bleStore[12] = list[14];
        bleStore[13] = list[15];
        bleStore[14] = list[16];
      }else if (list[1] == 5) {// 温度 温度单位 
        bleStore[0] = list[2];
        bleStore[1] = list[3];
      }else if (list[1] == 6) {// 开关灯状态 亮度
        bleStore[2] = list[2];
        bleStore[3] = list[3];
      }else if (list[1] == 7) {//延迟关灯状态 亮度
        bleStore[4] = list[2];
        bleStore[5] = list[3];
      }else if (list[1] == 8) {//是否12小时制
        bleStore[6] = list[2];
      }else if (list[1] == 9) {//整时报点
        bleStore[7] = list[2];
      }else if (list[1] == 10) {//音量
        bleStore[8] = list[2];
      }else if (list[1] == 11) {//铃声渐强
        bleStore[9] = list[2];
      }else if (list[1] == 12) {//倒计时开关状态 倒计时时间
        bleStore[10] = list[2];
        bleStore[11] = list[3];
      }else if (list[1] == 13) {//正计时开关状态 正计时时间
        bleStore[12] = list[2];
        bleStore[13] = list[3];
      }else if (list[1] == 14) {//闹钟响铃呼吸灯
        bleStore[14] = list[2];
      }

      app.store.setState({
        bleStore
      });
      list = [];
    });
    console.log('[蓝牙接收] 已设置监听');
  },


  // 发现服务和特征值
  discoverServicesAndCharacteristics(deviceId) {
    const that = this;
    wx.getBLEDeviceServices({
      deviceId,
      success(res) {
        console.log('[蓝牙服务] 发现服务列表:', res.services);
        let serviceFound = false;
        for (const service of res.services) {
          if (serviceFound) break;

          wx.getBLEDeviceCharacteristics({
            deviceId,
            serviceId: service.uuid,
            success(charRes) {
              if (serviceFound) return;
              console.log(`[蓝牙特征值] 服务 ${service.uuid} 下的特征值:`, charRes.characteristics);

              const writableChar = charRes.characteristics.find(c => c.properties.write || c.properties.writeNoResponse);
              const notifiableChar = charRes.characteristics.find(c => c.properties.notify || c.properties.indicate);

              if (writableChar) {
                console.log('[蓝牙特征值] 找到可写特征值:', writableChar.uuid);
                that.setData({
                  serviceId: service.uuid,
                  characteristicId: writableChar.uuid,
                });
                serviceFound = true;

                if (notifiableChar) {
                  //把 di 和 找到可写特征值 保持vuex
                  let {
                    bleUser
                  } = app.store.getState();
                  bleUser.deviceId = deviceId;
                  bleUser.serviceId = service.uuid;
                  bleUser.characteristicId = notifiableChar.uuid;
                  app.store.setState({
                    bleUser
                  });
                  /**********************************/
                  wx.notifyBLECharacteristicValueChange({
                    deviceId: deviceId,
                    serviceId: service.uuid,
                    characteristicId: notifiableChar.uuid,
                    state: true,
                    type: 'notification',
                    success() {
                      console.log('[蓝牙通知] 已开启特征值通知:', notifiableChar.uuid);
                      ble_send_date(0); //发送时钟数据给蓝牙
                      ble_send_date(4); //查询闹钟1
                      ble_send_date(5); //查询闹钟2
                      ble_send_date(6); //查询闹钟3
                      ble_send_date(7); //查询所有其他设置的参数
                      ble_send_date(22); //播放连接成功提示音
                    },
                    fail(err) {
                      console.error('[蓝牙通知] 开启通知失败:', err);
                    }
                  });
                }
              }
            },
            fail(charErr) {
              console.error(`[蓝牙特征值] 获取服务 ${service.uuid} 的特征值失败:`, charErr);
            }
          });
        }
        setTimeout(() => {
          if (!that.data.characteristicId) {
            wx.showToast({
              title: '未找到可写特征值',
              icon: 'none'
            });
            console.error('搜索完毕，未找到可写特征值');
          }
        }, 1000);
      },
      fail(err) {
        wx.showToast({
          title: '获取服务失败',
          icon: 'none'
        });
        console.error('[蓝牙服务] 获取服务失败:', err);
      }
    });
  },

  //处理闹钟数据
  update_alarm_list(list) {
    let {
      alarm_list
    } = app.store.getState();
    if (list[1] == 1 || list[1] == 2 || list[1] == 3) {
      alarm_list[list[1] - 1].alarm_tm_hour1 = list[2];
      alarm_list[list[1] - 1].alarm_tm_min1 = list[3];
      alarm_list[list[1] - 1].alarm_state1 = list[4];
      alarm_list[list[1] - 1].alarm_play_time1 = list[5];
      alarm_list[list[1] - 1].alarm_ring_tone1 = list[6];
      alarm_list[list[1] - 1].alarm_over_sleeping1 = list[7];
    }
    app.store.setState({
      alarm_list
    });
  },

  onBluetoothDeviceConnect: function (res) {
    // 当设备连接成功时触发
    console.log('设备连接成功', res.device);
    this.setData({
      connectedDevice: res.device // 更新数据绑定的连接设备信息
    });
  },
  onBluetoothDeviceDisconnect: function (res) {
    // 当设备断开连接时触发
    console.log('设备断开连接', res.device);
    this.setData({
      connectedDevice: null // 清除已连接设备信息
    });
  },

  onLoad() {
    //进入搜索一次
    this.onSearchConnect();
  }
})